//
//  BDShopPayViewController.m
//  iOS_beboy
//
//  Created by wen on 2017/9/19.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDShopPayViewController.h"
#import "BDUserModel.h"
#import "BDShopDetailModel.h"
#import "BDPayViewController.h"
@interface BDShopPayViewController ()
{
    BOOL requestFail;
}
@property (nonatomic, strong) BDShopDetailModel *shopModel;
@property (nonatomic, strong) UITextField *textField;

@end

@implementation BDShopPayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = ASLocalizedString(@"付款");
    [self custom_textField];
    [self requestDatasource];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if (requestFail == NO) {
        [_textField becomeFirstResponder];
    }
}

- (void)requestDatasource{
    [MBManager showLoadingAlert:ASLocalizedString(@"加载中")clickHidden:NO clickBlock:nil];
    NSString *headerVale = [BDUserModel getHeaderValidation];
    NSString *url = [KBDBaseURL stringByAppendingString:[NSString stringWithFormat:@"shop/%@", self.shop_id]];
    
    RACSignal *signal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headerVale automaticProcessingError:NO] execute:nil];
    [signal subscribeNext:^(id  _Nullable x) {
        [MBManager hideAlert];
        self.shopModel = [BDShopDetailModel mj_objectWithKeyValues:x];
        if (self.shopModel) {
            requestFail = NO;
            [self layoutSubviews];
            return;
        }
        requestFail = YES;
        [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"该商家不存在或已关闭")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:^(NSInteger index) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }];
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {
        requestFail = YES;
        [MBManager hideAlert];
        [self showErrorViewWithTapBlock:^{
            [self requestDatasource];
        }];
    }];
}

- (void)layoutSubviews{
    
    UIView *topView = [[UIView alloc] init];
    UIImageView *coverImageView = [[UIImageView alloc] init];
    coverImageView.size = CGSizeMake(41, 41);
    [coverImageView sd_setImageWithURL:[NSURL URLWithString:self.shopModel.cover] placeholderImage:[UIImage imageNamed:@"shop_moren.jpg"]];
    coverImageView.layer.masksToBounds = YES;
    coverImageView.layer.cornerRadius = coverImageView.width / 2.0;
    [topView addSubview:coverImageView];
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.font = [UIFont systemFontOfSize:14];
    titleLabel.textColor = [UIColor colorWithHexString:@"#1c1c1c"];
    titleLabel.text = self.shopModel.title;
    [titleLabel sizeToFit];
    titleLabel.left = coverImageView.right + 10;
    titleLabel.centerY = coverImageView.centerY;
    [topView addSubview:titleLabel];
    
    topView.size = CGSizeMake(titleLabel.right, coverImageView.bottom);
    topView.centerX = kBDScreenWidth / 2.0;
    topView.top = kBDTopHeight + 20;
    [self.view addSubview:topView];
    
    _textField.top = topView.bottom + 10;
    _textField.centerX = topView.centerX;
}

- (void)custom_textField{
    UILabel *tishiLabel = [[UILabel alloc] init];
    tishiLabel.font = [UIFont systemFontOfSize:17];
    tishiLabel.textColor = [UIColor colorWithHexString:@"#1c1c1c"];
    tishiLabel.text = ASLocalizedString(@"输入消费金额");
    [tishiLabel sizeToFit];
    tishiLabel.width += 20;
    tishiLabel.textAlignment = NSTextAlignmentRight;
    
    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 0)];
    
    _textField = [[UITextField alloc] init];
    _textField.size = CGSizeMake(kBDScreenWidth - 30, 62);
    _textField.layer.borderColor = KBDColorBlue.CGColor;
    _textField.layer.borderWidth = 1;
    _textField.leftView = tishiLabel;
    _textField.leftViewMode = UITextFieldViewModeAlways;
    _textField.rightView = rightView;
    _textField.rightViewMode = UITextFieldViewModeAlways;
    _textField.layer.masksToBounds = YES;
    _textField.layer.cornerRadius = 3;
    _textField.backgroundColor = [UIColor whiteColor];
    _textField.text = @"¥ ";
    _textField.font = [UIFont systemFontOfSize:22];
    _textField.textAlignment = NSTextAlignmentRight;
    [self.view addSubview:_textField];
    
    
    CGFloat width = kBDScreenWidth / 4;
    CGFloat height = 277 / 375.0 * kBDScreenWidth / 4;
    UIView *keyboardView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, height * 4)];
    
    NSArray *btnArr = @[@{@"type":@"label", @"content":@"1"},@{@"type":@"label", @"content":@"2"},@{@"type":@"label", @"content":@"3"},@{@"type":@"image", @"content":@"keyboard_del"},
  @{@"type":@"label", @"content":@"4"},@{@"type":@"label", @"content":@"5"},@{@"type":@"label", @"content":@"6"},@{@"type":@"label", @"content":ASLocalizedString(@"确认\n支付")},
                        @{@"type":@"label", @"content":@"7"},@{@"type":@"label", @"content":@"8"},@{@"type":@"label", @"content":@"9"},
  @{@"type":@"image", @"content":@"keyboard_down"},@{@"type":@"label", @"content":@"0"},@{@"type":@"image", @"content":@"keyboard_dot"}];
    
    int index = 0;
    
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4; j++) {
            if (i >= 2 && j == 3) {
                continue;
            }
            NSDictionary *dic = btnArr[index];
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            if ([[dic objectForKey:@"type"] isEqualToString:@"label"]) {
                [button setTitle:dic[@"content"] forState:UIControlStateNormal];
                [button setTitleColor:[UIColor colorWithHexString:@"#4c4c4c"] forState:UIControlStateNormal];
                button.titleLabel.font = [UIFont systemFontOfSize:27];
                button.titleLabel.numberOfLines = 0;
            }else{
                [button setBackgroundImage:[UIImage imageNamed:dic[@"content"]] forState:UIControlStateNormal];
            }
            button.frame = CGRectMake(width * j, height * i, width, height);
            button.backgroundColor = [UIColor whiteColor];
            if (i == 1 && j == 3) {
                button.frame = CGRectMake(width * j, height * i, width, height * 3);
                button.backgroundColor = KBDColorBlue;
                [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            }
            [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                if (index == 3) {
                    //删除
                    [self textFieldChangeString:nil isDeleted:YES];
                }else if (index == 7) {
                    //确认支付
                    NSDecimalNumber *price = nil;
                    if (_textField.text.length <= 2) {
                        price = [NSDecimalNumber decimalNumberWithString:@"0"];
                    }else {
                        NSString *subString = [_textField.text substringFromIndex:2];
                        price = [NSDecimalNumber decimalNumberWithString:subString];
                    }
                    NSComparisonResult result_clearrate_float = [price compare:[NSDecimalNumber decimalNumberWithString:@"0"]];
                    if (result_clearrate_float != 1) {
                        [MBManager showBriefAlert:ASLocalizedString(@"请输入正确的金额")clickHidden:YES clickBlock:nil];
                        return ;
                    }
                    
                    BDPayViewController *payVC = [[BDPayViewController alloc] init];
                    payVC.productId = self.shop_id;
                    payVC.payType = BDProductPayTypeTransferToShop;
                    payVC.price = price;
                    [self.navigationController pushViewController:payVC animated:YES];
                }else if (index == 11) {
                    //回收键盘
                    [_textField resignFirstResponder];
                }else if (index == 13) {
                    //dot
                    [self textFieldChangeString:@"." isDeleted:NO];
                }else {
                    [self textFieldChangeString:dic[@"content"] isDeleted:NO];
                }
            }];
            button.endWindowEditingWhenTouch = NO;
            [keyboardView addSubview:button];
            index++;
        }
    }
    
    for (int i = 0; i < 5; i++) {
        UIView *line_v = [[UIView alloc] init];
        line_v.size = CGSizeMake(1, height * 4);
        line_v.centerX = width * i;
        line_v.backgroundColor = [UIColor colorWithHexString:@"#e5e5e5"];
        [keyboardView addSubview:line_v];
        
        UIView *line_h = [[UIView alloc] init];
        if (i == 2 || i == 3) {
            line_h.size = CGSizeMake(width * 3, 1);
        }else{
            line_h.size = CGSizeMake(width * 4, 1);
        }
        
        line_h.centerY = height * i;
        line_h.backgroundColor = [UIColor colorWithHexString:@"#e5e5e5"];
        [keyboardView addSubview:line_h];
        
        line_v.userInteractionEnabled = NO;
        line_h.userInteractionEnabled = NO;
    }
    _textField.inputView = keyboardView;
    [_textField reloadInputViews];
}

- (void)textFieldChangeString:(NSString *)string isDeleted:(BOOL)isDeleted{
    NSString *curentText = _textField.text;
    if (isDeleted) {
        if (curentText.length > 2) [_textField deleteBackward];
    }else {
        if ([string containsString:@"."]) {
            //如果当前包含小数点，那么不处理
            if (![curentText containsString:@"."]) {
                //判断小数点前面没有整数部分，那么要拼接一个0
                if (curentText.length <= 2) {
                    _textField.text = [curentText stringByAppendingString:@"0."];
                }else{
                    [_textField insertText:@"."];
                }
            }
        }else {
            //当输入数字的时候，整数部分不超过5位，小数部分不超过2位
            if ([curentText containsString:@"."]) {
                NSRange dotRange = [curentText rangeOfString:@"."];
                if (dotRange.location + dotRange.length + 2 > curentText.length) {
                    [_textField insertText:string];
                }
            }else{
                if (curentText.length < 7) {
                    [_textField insertText:string];
                }
            }
        }
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    BOOL isDeleted = range.length == 0;
    NSString *curentText = textField.text;
    if (isDeleted) {
        if (curentText.length <= 2) return NO;
    }else {
        if ([string containsString:@"."]) {
            //如果当前包含小数点，那么不处理
            if ([curentText containsString:@"."]) {
                return NO;
            }else{
                //判断小数点前面没有整数部分，那么要拼接一个0
                if (curentText.length <= 2) {
                    textField.text = [curentText stringByAppendingString:@"0."];
                }
            }
        }else {
            //当输入数字的时候，整数部分不超过5位，小数部分不超过2位
            if ([curentText containsString:@"."]) {
                NSRange dotRange = [curentText rangeOfString:@"."];
                if (dotRange.location + dotRange.length + 2 >= curentText.length) {
                    return NO;
                }
            }else{
                if (curentText.length >= 7) {
                    return NO;
                }
            }
        }
    }
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
